package edu.pku.sei.pgie.persistence.xml.template;

import edu.pku.sei.pgie.analyzer.internal.*;
import edu.pku.sei.pgie.analyzer.util.*;

import java.util.*;

import edu.pku.sei.pgie.analyzer.core.SymbolTable;
import edu.pku.sei.pgie.analyzer.core.Token;

public class XMLTokenSerializer
{
  protected static String nl;
  public static synchronized XMLTokenSerializer create(String lineSeparator)
  {
    nl = lineSeparator;
    XMLTokenSerializer result = new XMLTokenSerializer();
    nl = null;
    return result;
  }

  protected final String NL = nl == null ? (System.getProperties().getProperty("line.separator")) : nl;
  protected final String TEXT_1 = "";
  protected final String TEXT_2 = NL + "<class name=\"";
  protected final String TEXT_3 = "\" id=\"";
  protected final String TEXT_4 = "\">" + NL + "\t<tokens>" + NL + "\t";
  protected final String TEXT_5 = NL + "\t\t<token postition=\"";
  protected final String TEXT_6 = "\">" + NL + "\t\t\t<value><![CDATA[";
  protected final String TEXT_7 = "]]></value>" + NL + "\t\t</token>" + NL + "\t";
  protected final String TEXT_8 = NL + "\t</tokens>" + NL + "\t<source-code>" + NL + "\t\t<![CDATA[";
  protected final String TEXT_9 = "]]>" + NL + "\t</source-code>" + NL + "</class>";

  public String generate(Object argument)
  {
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append(TEXT_1);

	Object[] args = (Object[]) argument;
	Tokenizer tokenizer = (Tokenizer) args[0];
	SymbolTable symbolTable = (SymbolTable) args[1];
	String[] fqns = tokenizer.getFqns();

    for(int i = 0;i < fqns.length;i ++) {
	String id = null;
	if(symbolTable != null)
		id = symbolTable.resolveRefId(fqns[i]);
	else
		id = new Integer(i).toString();

    stringBuffer.append(TEXT_2);
    stringBuffer.append(fqns[i]);
    stringBuffer.append(TEXT_3);
    stringBuffer.append(id);
    stringBuffer.append(TEXT_4);

		List tokens = tokenizer.getTokenByFqn(fqns[i]);
		Iterator iterator = tokens.iterator();
		while(iterator.hasNext()) {
			Token token = (Token)iterator.next();

    stringBuffer.append(TEXT_5);
    stringBuffer.append(token.position);
    stringBuffer.append(TEXT_6);
    stringBuffer.append(token.token);
    stringBuffer.append(TEXT_7);
    }
    stringBuffer.append(TEXT_8);
    stringBuffer.append(tokenizer.getSourceByFqn(fqns[i]));
    stringBuffer.append(TEXT_9);
    }
    return stringBuffer.toString();
  }
}
